package com.holly.unit.timer.modular.dataServer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.holly.unit.timer.api.TimerDataServer;
import com.holly.unit.timer.api.TimerExeService;
import com.holly.unit.timer.api.enums.TimerJobStatusEnum;
import com.holly.unit.timer.modular.entity.SysTimers;
import com.holly.unit.timer.modular.service.SysTimersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.UUID;

@Service
public class SynchDataServer implements TimerDataServer {


    @Autowired
    private SysTimersService sysTimersService;
    @Resource
    private TimerExeService timerExeService;

    /**
     * 验证是否执行  执行修改该任务的状态
     *
     * @param cron
     * @param taskId
     * @return
     */
    @Override
    public boolean checkExecute(String cron, String taskId) {
        SysTimers timers = sysTimersService.getById(taskId);

        if(timers.getJobStatus().equals(TimerJobStatusEnum.STOP.getCode())){
            return  false;
        }

        //判断表达式是否相同
        try {
            if (!timers.getCron().equals(cron) && timers.getJobStatus().equals(TimerJobStatusEnum.RUNNING.getCode())) {
                //注销服务再重启服务
                CronUtil.remove(taskId);
                timerExeService.startTimer(String.valueOf(timers.getTimerId()), timers.getCron(), timers.getActionClass(), timers.getParams());
            }
        }catch (Exception ex){
            System.out.println("重启起服务报错");
        }

        UUID uuid = UUID.randomUUID();
        if (ObjectUtil.isNull(timers.getVersion())) {
            timers.setVersion(uuid.toString());
            timers.setExecuteDate(getNextExecuteDate(cron));
            boolean r= sysTimersService.updateById(timers);
            if(r){
                System.out.print("第一次验证成功");
            }else{
                System.out.print("第一次验证失败");
            }
            return r;
        }
        Long executeDate = getExecuteDate();
        if (executeDate.longValue() >= timers.getExecuteDate().longValue()) {
            String version = timers.getVersion();
            timers.setVersion(uuid.toString());
            timers.setExecuteDate(getNextExecuteDate(cron));
            Boolean r= sysTimersService.update(timers, new QueryWrapper<SysTimers>().eq("version", version));
            if(r){
                System.out.print("定时任务提交验证成功");
            }else{
                System.out.print("定时任务提交验证失败");
            }
            return r;
        }else{
            System.out.print("定时任务时间验证失败");
        }
        return false;
    }

    private Long getNextExecuteDate(String cron) {
        CronExpression cronExpression = CronExpression.parse(cron);
        LocalDateTime dateTime = cronExpression.next(LocalDateTime.now());
        return dateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    private Long getExecuteDate() {
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

}
